package com.cskaoyan.gateway.controller.user;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.ILoginService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.UserLoginRequest;
import com.mall.user.dto.UserLoginResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class LoginController {
    //调用验证码服务
    @Reference(check = false,timeout = 2000,retries = 0)
    private IKaptchaService kaptchaService;

    @Reference(check = false,timeout = 2000,retries = 0)
    private ILoginService loginService;

    @Anoymous
    @PostMapping("/login")
    public ResponseData login(@RequestBody Map<String,String> map, HttpServletRequest request){
        String username = map.get("userName");
        String password = map.get("userPwd");
        String captcha = map.get("captcha");

        //校验验证码
        RegisterController registerController = new RegisterController();
        ResponseData responseData = registerController.kaptcha(captcha,request);
        if (responseData != null){
            return responseData;
        }

        //查询用户信息
        UserLoginRequest userLoginRequest = new UserLoginRequest();
        userLoginRequest.setPassword(password);
        userLoginRequest.setUserName(username);
        UserLoginResponse userLoginResponse = loginService.longin(userLoginRequest);
        if (userLoginResponse == null){
            return new ResponseUtil<>().setErrorMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
        }

        return new ResponseUtil<>().setData(userLoginResponse);
    }

}
